﻿CREATE PROCEDURE dbo.SP_Countries_SELECT
@StartIndex INT = NULL,
@lenght INT =  NULL ,
@OrderColume nvarchar(256) = NULL
, @CountryId Int   =  NULL 
, @CountryName NVarChar (256)  =  NULL 
	AS
			WITH CTE_Countries AS
			( 
			SELECT
 							CountryId,
								CountryName,
							ROW_NUMBER() OVER (ORDER BY 
        	CASE 
									WHEN @OrderColume='CountryId' THEN CountryId
						 
						WHEN @OrderColume='CountryName' THEN CountryName
									ELSE 
							    CountryId
					        	END
			) AS "RowNumber"
  			FROM Countries 
			where 
								(CountryId = @CountryId OR @CountryId Is Null)
										AND(CountryName LIKE @CountryName OR @CountryName Is Null)
								)
			SELECT  *
			FROM CTE_Countries
			WHERE  (RowNumber >= @StartIndex OR @StartIndex Is Null) AND (RowNumber <= @StartIndex+@lenght OR (@StartIndex Is Null and @lenght Is Null))
			Return (select @@ROWCOUNT)
			